﻿using System;
using System.Threading;
using System.Threading.Tasks;

namespace Task取消
{
    class Program
    {
        static void Main(string[] args)
        {

            #region Thread方式
            //var t = new Thread(()=> {
            //    bool isStop = false;
            //    int a = 0;
            //    while (!isStop) {
            //        a++;
            //        Thread.Sleep(300);
            //        Console.WriteLine(DateTime.Now);
            //        if (a > 5)
            //        { 
            //            isStop = true;
            //        }
            //    }
            //});
            //t.Start();
            #endregion
            #region CancellationTokenSource 取消
            ////CancellationTokenSource source = new CancellationTokenSource();
            //// 1秒后取消任务
            //CancellationTokenSource source = new CancellationTokenSource(1000);
            //// 注册取消任务回调
            //source.Token.Register(() => {
            //    Console.WriteLine("任务被取消了。。。");
            //});

            //Task.Factory.StartNew(() => {
            //    while (!source.IsCancellationRequested)
            //    {
            //        Thread.Sleep(100);
            //        Console.WriteLine($"tid={Thread.CurrentThread.ManagedThreadId},date={DateTime.Now}");    
            //    }
            //},source.Token);

            //// 延迟取消，1s 后取消，也可以在CancellationTokenSource  构造函数中实现 
            ////source.CancelAfter(new TimeSpan(0,0,1));
            ////Thread.Sleep(1000);
            ////source.Cancel(); 
            #endregion
            #region 组合方式取消
            //var source1= new CancellationTokenSource();
            //// 因为 s3 是个组合，只要s1或者s2，任意一个 取消，那么s3 也会跟这 取消的。
            //source1.Cancel();
            //var source2 = new CancellationTokenSource();
            //var source3 = CancellationTokenSource.CreateLinkedTokenSource(source1.Token,source2.Token);

            //Console.WriteLine($"s1={source1.IsCancellationRequested},s2={source2.IsCancellationRequested},s3={source3.IsCancellationRequested}");

            #endregion
            #region  取消后跑出异常
            CancellationTokenSource source = new CancellationTokenSource(1000);
            source.Token.Register(() =>
            {
                Console.WriteLine("任务被取消了。。。");
            });

            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    //如果取消 就抛出一个异常
                    source.Token.ThrowIfCancellationRequested();
                    Thread.Sleep(100);
                    Console.WriteLine($"tid={Thread.CurrentThread.ManagedThreadId},date={DateTime.Now}");
                }
            }, source.Token);

           
            #endregion
            Console.Read();
        }
    }
}
